<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="optType  != 'view'"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xm:projectUser:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table border v-loading="loading" :data="projectUserList" @selection-change="handleSelectionChange">
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="项目角色" align="center" prop="projectRole" />
      <el-table-column label="权限" align="center" prop="permissionsName" />
      <el-table-column label="所在部门" align="center" prop="departmentName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="optType  != 'view'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xm:projectUser:edit']"
          >修改</el-button>
          <el-button
            v-if="optType  != 'view'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xm:projectUser:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" readonly>
            <el-button
              slot="append"
              @click="handleSelectUser"
              icon="el-icon-search">
            </el-button>
          </el-input>
          <UserSelect ref="userSelect" @onSelected="onUserSelected" ></UserSelect>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" readonly placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="所在部门" prop="departmentName">
          <el-input v-model="form.departmentName" readonly placeholder="请输入所在部门" />
        </el-form-item>
        <el-form-item label="项目角色" prop="projectRole">
          <el-input v-model="form.projectRole" placeholder="请输入项目角色" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-cascader :key="cascaderKey" @change="handleChange" v-model="form.permissions" style="width: 100%" :options="dataOptions" :props="defaultProps" placeholder="请选择权限" :show-all-levels="false"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProjectUser, getProjectUser, delProjectUser, addProjectUser, updateProjectUser } from "@/api/mes/xm/projectUser";
import UserSelect from "@/components/userSelect/single.vue";
import {treeSelect} from "@/api/mes/xm/templateInfo";

export default {
  name: "ProjectUser",
  components: {UserSelect},
  props: {
    projectId: {
      type: [Number],
      required: true
    },
    projectName:{
      type: [String],
      required: true
    },
    templateId:{
      type: [Number],
      required: true
    },
    optType:{
      type: [String],
      required: true
    }
  },
  data() {
    return {
      cascaderKey:0,
      dataList:[],
      defaultProps: {
        children: "children",
        label: "label",
        value: "id",
        checkStrictly: true,
        emitPath:false
      },
      dataOptions: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目用户表格数据
      projectUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,        name: null,        projectRole: null,        permissions: null,        permissionsName: null,        departmentId: null,        departmentName: null,        projectId: null,        projectName: null,        remarks: null,      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],        projectRole: [
          { required: true, message: "项目角色不能为空", trigger: "blur" }
        ],        departmentName: [
          { required: true, message: "所在部门不能为空", trigger: "blur" }
        ],        permissions: [
          { required: true, message: "请选择权限", trigger: "blur" }
        ],      }
    };
  },
  created() {
    this.getList();
    this.getTreeSelect(this.templateId);
  },
  watch: {
    projectId(newVal) {
      if (newVal) {
        this.projectId=newVal;
        this.getList();
        this.getTreeSelect(this.templateId)
      }
    },
    optType(newVal) {
      if (newVal) {
        this.optType=newVal;
      }
    },
    templateId(newVal){
      if (newVal) {
        this.templateId=newVal;
       /* this.getList();
        this.getTreeSelect(this.templateId)*/
      }
    }
  },
  methods: {
    handleChange(value){
      this.form.permissionsName = this.findLabels(value, this.dataOptions);
    },
    findLabels(value, data) {
      const node = this.findNode(value, data);
      if (node) {
        return node.label;
      }
      return null;
    },
    findNode(value, data) {
      for (const item of data) {
        if (item.id === value) {
          return item;
        }
        if (item.children) {
          const result = this.findNode(value, item.children);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    getTreeSelect(id) {
      treeSelect(id).then(response => {
        this.dataOptions = response.data.tree;
        if(this.dataOptions.length>0) {
          this.dataOptions[0].label = "全部阶段";
        }
        this.dataList = response.data.list;
        //this.findItemById(this.dataList, id);
      })
    },
    handleSelectUser(){
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj){
      if(obj != undefined && obj != null){
        this.form.userName = obj.userName;
        this.form.name = obj.nickName;
        this.form.departmentId = obj.dept.deptId;
        this.form.departmentName = obj.dept.deptName;
      }
    },
    /** 查询项目用户列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectId = this.projectId;
      listProjectUser(this.queryParams).then(response => {
        this.projectUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        userName: null,        name: null,        projectRole: null,        permissions: null,        permissionsName: null,        departmentId: null,        departmentName: null,        projectId: null,        projectName: null,        remarks: null,        createBy: null,        createTime: null,        updateBy: null,        updateTime: null,        tenantId: null      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.cascaderKey += 1;
      this.open = true;
      this.title = "添加项目用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProjectUser(id).then(response => {
        this.form = response.data;
        this.cascaderKey += 1;
        this.open = true;
        this.title = "修改项目用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.projectId = this.projectId;
          this.form.projectName = this.projectName;
          if (this.form.id != null) {
            updateProjectUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProjectUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目用户编号为"' + ids + '"的数据项？').then(function() {
        return delProjectUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xm/projectUser/export', {
        ...this.queryParams
      }, `projectUser_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
